package com.dhz.common.id.redis;

import org.apache.commons.lang3.time.StopWatch;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.concurrent.CountDownLatch;

/**
 * @author FY
 * @since 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring-id-test.xml"})
public class IdGenTemplate2 {
    private static final Logger logger = LoggerFactory.getLogger(IdGenTemplate2.class);

    @Autowired
    private IdGeneratorTemplate2 template;

    @Test
    public void testGeneratorId() {
        IdObject id = template.next("user", 6452231512l);
        logger.info(id.toString());
    }

    @Test
    public void testGeneratorBatchId() {
        for (int i = 0; i < 1000; i++) {
            IdObject id = template.next("user", 6452231512l);
            logger.info(id.toString());
        }
    }

    @Test
    public void testBenchmark() throws InterruptedException {
        int threadCount = 20;
        final int genCount = 100000;
        StopWatch watch = new StopWatch();

        final CountDownLatch latch = new CountDownLatch(threadCount);

        watch.start();
        for (int i = 0; i < threadCount; ++i) {
            Thread thread = new Thread() {
                public void run() {
                    for (int j = 0; j < genCount; ++j) {
                        IdObject id = template.next("user", 6452231512l);
                    }
                    latch.countDown();
                }
            };
            thread.start();
        }

        latch.await();
        watch.stop();

        System.err.println("time:" + watch);
        System.err.println("speed:" + genCount * threadCount / (watch.getTime() / 1000.0));

    }
}
